/*
 * @Description:试题作业
 * @Author: ldx
 * @Date: 2022-09-18 22:35:41
 * @LastEditors: ldx
 * @LastEditTime: 2022-09-29 00:12:04
 */

import { DownOutlined, UploadOutlined } from '@ant-design/icons'
import { useAntdTable, useRequest } from 'ahooks'
import {
  Button,
  Col,
  div,
  Dropdown,
  Form,
  Input,
  Menu,
  message,
  Modal,
  Popconfirm,
  Row,
  Table,
  Upload
} from 'antd'
const { TextArea } = Input
import moment from 'moment'
import { useState } from 'react'

import {
  createExam,
  deleteExam,
  downloadExam,
  previewExam,
  queryDetails,
  queryExam,
  templateDownloadExam,
  updateExam
} from '@/api/homework/exam'
import { TextTooltip } from '@/components'
import AuthButton from '@/components/authButton'
import { PageContainer } from '@/components/pageContainer'

import Preview from './preview'
const Exam = () => {
  const [form] = Form.useForm()
  const [addForm] = Form.useForm()
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [isModalOpenDetails, setIsModalOpenDetails] = useState(false)
  const [isModalOpenPreview, setIsModalOpenPreview] = useState(false)
  const [details, setDetails] = useState<any>()
  const [previewData, setPreviewData] = useState<any>()
  const [fileList, setFileList] = useState<any>([])
  /** 试题作业列表 */
  const { tableProps, search } = useAntdTable(queryExam, {
    form
  })

  /** 试题作业详情 */
  const { runAsync: runQueryDetails } = useRequest(queryDetails, {
    manual: true,
    onSuccess: (res) => {
      setDetails(res.data)
    }
  })
  /** 试题作业删除 */
  const { runAsync: runDeleteExam } = useRequest(deleteExam, {
    manual: true,
    onSuccess: () => {
      search.submit()
    }
  })
  /** 试题作业预览*/
  const { runAsync: runPreviewExam } = useRequest(previewExam, {
    manual: true,
    onSuccess: (res) => {
      setPreviewData(res.data)
    }
  })
  /** 试题作业下载 */
  const { runAsync: runDownloadExam } = useRequest(downloadExam, {
    manual: true,
    onSuccess: (res) => {
      const filename = res.headers['content-disposition']
        .split(';')[1]
        .split('=')[1]
      // 创建隐藏的可下载链接
      const eleLink = document.createElement('a')
      eleLink.download = decodeURIComponent(filename)
      eleLink.style.display = 'none'
      // 字符内容转变成blob地址
      const blob = new Blob([res.data], { type: 'text/html' })
      eleLink.href = URL.createObjectURL(blob)
      // 触发点击
      document.body.appendChild(eleLink)
      eleLink.click()
      // 然后移除
      document.body.removeChild(eleLink)
      message.success('下载成功')
    }
  })
  /** 试题作业下载 */
  const { runAsync: runTemplateDownloadExam } = useRequest(
    templateDownloadExam,
    {
      manual: true,
      onSuccess: (res) => {
        const filename = res.headers['content-disposition']
          .split(';')[1]
          .split('=')[1]
        // 创建隐藏的可下载链接
        const eleLink = document.createElement('a')
        eleLink.download = decodeURIComponent(filename)
        eleLink.style.display = 'none'
        // 字符内容转变成blob地址
        const blob = new Blob([res.data], { type: 'text/html' })
        eleLink.href = URL.createObjectURL(blob)
        // 触发点击
        document.body.appendChild(eleLink)
        eleLink.click()
        // 然后移除
        document.body.removeChild(eleLink)
        // message.success('模版下载成功')
      }
    }
  )
  /** 创建试题作业 */
  const { runAsync: runCreateExam } = useRequest(createExam, {
    manual: true,
    onSuccess: () => {
      search.reset()
      setIsModalOpen(false)
      addForm.resetFields()
      setDetails(undefined)
      message.success('创建成功')
    }
  })
  /** 更新试题作业 */
  const { runAsync: runUpdateExam } = useRequest(updateExam, {
    manual: true,
    onSuccess: () => {
      search.reset()
      setIsModalOpen(false)
      addForm.resetFields()
      setDetails(undefined)
      message.success('更新成功')
    }
  })
  const columns: any[] = [
    {
      title: '序号',
      width: 60,
      align: 'center',
      dataIndex: 'a',
      render: (text: string, record: any, index: number) => {
        return <span>{index + 1}</span>
      }
    },
    {
      title: '试题名称',
      align: 'center',
      dataIndex: 'examName'
    },
    // {
    //   title: '摘要',
    //   align: 'center',
    //   ellipsis: true,
    //   dataIndex: 'description'
    // },
    {
      title: '试题文件名称',
      align: 'center',
      ellipsis: true,
      dataIndex: 'fileName'
    },
    {
      title: '试题文件路径',
      align: 'center',
      ellipsis: true,
      dataIndex: 'filePath'
    },
    {
      title: '创建时间',
      align: 'center',
      dataIndex: 'createTime',
      render: (text: string) => {
        return <span>{moment(text).format('YYYY-MM-DD HH:mm:ss')}</span>
      }
    },
    {
      title: '创建人',
      align: 'center',
      dataIndex: 'creatorName'
    },
    {
      title: '操作',
      width: 300,
      align: 'center',
      key: 'action',
      render: (text: number, record: any) => (
        <div>
          <AuthButton
            auth={['/**', '/exam/**', '/exam/details/{id}']}
            type="link"
            onClick={() => {
              setIsModalOpenDetails(true)
              runQueryDetails(record.id)
            }}
          >
            详情
          </AuthButton>
          <Popconfirm
            title="确认下载?"
            onConfirm={() => runDownloadExam(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <AuthButton
              auth={['/**', '/exam/**', '/exam/download/{id}']}
              type="link"
            >
              {/* <a download href={`/ivr/exam/download/${record.id}`}>
                下载
              </a> */}
              下载
            </AuthButton>
          </Popconfirm>
          <AuthButton
            type="link"
            auth={['/**', '/exam/**', '/exam/update']}
            onClick={() => {
              // setRole(record)
              addForm.setFieldsValue(record)
              setIsModalOpen(true)
              setDetails(record)
              // setFileList([
              //   {
              //     uid: '1',
              //     name: record.fileName,
              //     status: 'done'
              //   }
              // ])
            }}
          >
            编辑
          </AuthButton>
          <Dropdown
            overlay={
              <Menu>
                <Menu.Item key="2">
                  <AuthButton
                    type="link"
                    auth={['/**', '/exam/**', '/exam/preview/{id}']}
                    onClick={() => {
                      // addForm.setFieldsValue(record)
                      // setIsModalOpen(true)
                      // setDetails(record)
                      setIsModalOpenPreview(true)
                      runPreviewExam(record.id)
                    }}
                  >
                    预览
                  </AuthButton>
                </Menu.Item>
                <Menu.Item key="1">
                  <Popconfirm
                    title="确认删除试题作业?"
                    onConfirm={() => runDeleteExam(record.id)}
                    okText="是"
                    cancelText="否"
                  >
                    <AuthButton
                      auth={['/**', '/exam/**', '/exam/delete/{id}']}
                      type="link"
                    >
                      删除
                    </AuthButton>
                  </Popconfirm>
                </Menu.Item>
              </Menu>
            }
          >
            <Button type="link">
              {' '}
              更多
              <DownOutlined />
            </Button>
          </Dropdown>
        </div>
      )
    }
  ]
  return (
    <>
      <PageContainer>
        <div>
          <Form form={form}>
            <Row gutter={24}>
              <Col span={5}>
                <Form.Item name="keyword">
                  <Input placeholder="请输入" />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Button onClick={() => search.submit()} type="primary">
                  搜索
                </Button>
              </Col>
              <Col span={11} className="flex justify-end">
                <AuthButton
                  className="mr-20px"
                  auth={['/**', '/exam/**', '/exam/template/download']}
                  onClick={() => runTemplateDownloadExam()}
                  type="primary"
                >
                  模板下载
                </AuthButton>
                <AuthButton
                  auth={['/**', '/exam/**', '/exam/create']}
                  onClick={() => setIsModalOpen(true)}
                  type="primary"
                >
                  创建
                </AuthButton>
              </Col>
            </Row>
          </Form>
          <Table
            columns={columns}
            scroll={{ x: 1400 }}
            rowKey={(record) => record.id}
            {...tableProps}
            pagination={{
              showTotal: (total, range) => {
                console.log('xxx', range)
                const num = Math.ceil(total / 10)
                return (
                  <span style={{ color: '#fff', marginRight: '10px' }}>
                    共{num}页/共{total}条结果
                  </span>
                )
              },
              ...tableProps.pagination
            }}
          />
        </div>
      </PageContainer>
      <Modal
        width={800}
        title="角色详情"
        visible={isModalOpenDetails}
        onOk={() => {
          setIsModalOpenDetails(false)
          setDetails(undefined)
        }}
        onCancel={() => {
          setIsModalOpenDetails(false)
          setDetails(undefined)
        }}
      >
        <div className="pl-20px details">
          <div>
            <span className="w-120px inline-block ">试题名称：</span>
            <span>{details?.examName}</span>
          </div>
          {/* <div>
            <span className="w-120px inline-block ">摘要：</span>
            <span>
              <TextTooltip className="w-520px">
                {details?.description}
              </TextTooltip>{' '}
            </span>
          </div> */}
          <div>
            <span className="w-120px inline-block ">试题文件名称：</span>
            <span className="inline-flex">
              <TextTooltip className="w-520px">{details?.fileName}</TextTooltip>{' '}
            </span>
          </div>
          <div>
            <span className="w-120px inline-block ">试题文件路径：</span>
            <span className="inline-flex">
              <TextTooltip className="w-520px">{details?.filePath}</TextTooltip>
            </span>
          </div>
          <div>
            <span className="w-120px inline-block ">创建时间：</span>
            <span>
              {moment(details?.createTime).format('YYYY-MM-DD HH:mm:ss')}
            </span>
          </div>
          <div>
            <span className="w-120px inline-block ">创建人：</span>
            <span>{details?.creatorName}</span>
          </div>
          <div>
            <span className="w-120px inline-block ">更新时间：</span>
            <span>
              {details?.updateTime
                ? moment(details?.updateTime).format('YYYY-MM-DD HH:mm:ss')
                : ''}
            </span>
          </div>
          <div>
            <span className="w-120px inline-block ">更新人：</span>
            <span>{details?.updateName}</span>
          </div>
        </div>
      </Modal>
      <Modal
        width={800}
        title={details ? '编辑试题作业' : '上传试题作业'}
        visible={isModalOpen}
        onOk={() => {
          if (details) {
            addForm.validateFields().then((values) => {
              runUpdateExam({
                ...details,
                ...values
              })
            })
          } else {
            addForm.validateFields().then((values) => {
              const formData = new FormData()
              formData.append('examFile', values.examFile.file)
              formData.append('examName', values.examName)
              // formData.append('description', values.description)
              runCreateExam(formData)
            })
          }
        }}
        onCancel={() => {
          setIsModalOpen(false)
          addForm.resetFields()
          setDetails(undefined)
        }}
      >
        <div>
          <Form
            name="register"
            initialValues={{
              prefix: '86'
            }}
            form={addForm}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
          >
            <Form.Item
              name="examName"
              label="试题名称"
              rules={[{ required: true, message: '请输入试题名称' }]}
            >
              <Input></Input>
            </Form.Item>
            {/* <Form.Item
              name="description"
              label="摘要"
              rules={[{ required: true, message: '请输入摘要' }]}
            >
              <TextArea rows={4}></TextArea>
            </Form.Item> */}
            {!details && (
              <Form.Item
                name="examFile"
                label="文件"
                rules={[{ required: true, message: '请上传文件' }]}
              >
                <Upload
                  className="basis-upload"
                  beforeUpload={(file) => {
                    setFileList([file])
                    return false
                  }}
                  fileList={fileList}
                  // customRequest={upload}
                  accept=".xlsx,.xls"
                  headers={{
                    authorization: 'authorization-text'
                  }}
                >
                  <Button icon={<UploadOutlined />}>上传</Button>
                </Upload>
              </Form.Item>
            )}
          </Form>
        </div>
      </Modal>
      {/* <Modal width={800}
        title={previewData?.examName}
        visible={isModalOpenPreview}
        onOk={() => {
          setIsModalOpenPreview(false)
        }}
        onCancel={() => {
          setIsModalOpenPreview(false)
        }}
        footer={null}
      >

      </Modal> */}
      {isModalOpenPreview && (
        <Preview data={previewData} setVisible={setIsModalOpenPreview} />
      )}
    </>
  )
}

export default Exam
